package com.atguigu.yygh.msm.controller;

import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.msm.service.MsmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author:ahang
 * @create:2022-09-07 19:12
 * @Description:
 */
@RestController
@RequestMapping("/api/msm")
public class MsmController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable("phone") String phone){
        //1.从redis中根据phone查找对应的code,如果存在则直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //2.发送验证码
        code = (long) (new Random().nextDouble() * 10000) + "";
        boolean send = msmService.send(phone, code);
        //3.将验证码存储到redis中
        if(send){
            //将短信存到redis中
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.DAYS);
            return R.ok().message("发送成功");
        }else{
            return R.error().message("发送失败");
        }
    }
}
